<template>
  <div class="q-pa-sm ">
    <q-card class="q-pa-sm search-css card-radius">
      <div style="color: #303CBB;font-size: 1.6rem;font-weight: 500;display: flex;align-items: center;">
        <div style="margin-left: 15px;">IGI report</div>
      </div>
      <q-card-section class="q-gutter-y-sm row">
        <q-item-label class="col-4 fal">Stock Code: </q-item-label>
        <q-input borderless v-model="createForm.data.stock_code" use-input input-debounce="0" hide-bottom-space lazy-rules
          class="col-8 fal input-css" :dense="true">
        </q-input>
        <q-item-label class="col-4 fal">Date Range </q-item-label>
        <div class="col-8  q-pa-sm" style="display: flex;align-items: center;justify-content: space-between;padding: 0;">
          <div style="width: 45%;">
            <q-input borderless class="input-css" v-model="createForm.data.start_date" dense hide-bottom-space readonly>
              <template v-slot:append>
                <img :src="delImg" alt="" v-if="createForm.data.start_date" @click="createForm.data.start_date = ''">
                <div v-else style="width:21px;height: 21px;"></div>
                <q-icon class="cursor-pointer ml4" size="md">
                  <q-img img :src="dateIcon">
                    <q-popup-proxy>
                      <q-date v-model="createForm.data.start_date">
                        <div class="row items-center justify-end">
                          <q-btn v-close-popup label="Close" color="primary" flat />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </q-img>
                </q-icon>
                <!-- <q-icon name="warning" class="warnHand" @click="createForm.data.start_date=''"/> -->
              </template>
            </q-input>
          </div>
          <div style="width: 10%;font-size: 25px;font-weight: 600;color: #CBCBCB;text-align: center;">-</div>
          <div style="width: 45%;">
            <q-input borderless class="input-css" v-model="createForm.data.end_date" dense hide-bottom-space readonly>
              <template v-slot:append>
                <img :src="delImg" alt="" v-if="createForm.data.end_date" @click="createForm.data.end_date = ''">
                <div v-else style="width:21px;height: 21px;"></div>
                <q-icon class="cursor-pointer ml4" size="md">
                  <q-img img :src="dateIcon">
                    <q-popup-proxy>
                      <q-date v-model="createForm.data.end_date">
                        <div class="row items-center justify-end">
                          <q-btn v-close-popup label="Close" color="primary" flat />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </q-img>
                </q-icon>
              </template>
            </q-input>
          </div>
        </div>
        <q-item-label class="col-4 fal">Completed</q-item-label>
        <div style="width: 60%">
          <q-checkbox v-model="createForm.data.completed" />
        </div>
        <div style="width: 100%;text-align: right;">
          <q-btn class="btnExport" @click="IgiReportDownload" style="font-size: 15.5px;font-weight: 400;" color="primary"
            icon-right="archive" no-caps><span class="btnExportText">Export PDF</span></q-btn>
        </div>
      </q-card-section>
    </q-card>
    <q-card class="q-pa-sm search-css card-radius">
      <div style="color: #303CBB;font-size: 1.6rem;font-weight: 500;display: flex;align-items: center;">
        <div style="margin-left: 15px;">CEWS Weekly Summary Report</div>
      </div>
      <q-card-section class="q-gutter-y-sm row">
        <q-item-label class="col-4 fal">Job No./Work order No.</q-item-label>
        <q-input borderless v-model="weeklylist.orderid" use-input input-debounce="0" hide-bottom-space lazy-rules
          class="col-8 fal input-css" :dense="true">
        </q-input>
        <q-item-label class="col-4 fal">Date Range </q-item-label>
        <div class="col-8  q-pa-sm" style="display: flex;align-items: center;justify-content: space-between;padding: 0;">
          <div style="width: 45%;">
            <q-input borderless class="input-css" style="width: 100%;" v-model="weeklylist.datefrom" dense hide-bottom-space
                     readonly>
              <template v-slot:append>
                <img :src="delImg" alt="" v-if="weeklylist.datefrom" @click="weeklylist.datefrom = ''">
                <div v-else style="width:21px;height: 21px;"></div>
                <q-icon class="cursor-pointer ml4" size="md">
                  <q-img img :src="dateIcon">
                    <q-popup-proxy>
                      <q-date v-model="weeklylist.datefrom" :options="optionsFn">
                        <div class="row items-center justify-end">
                          <q-btn v-close-popup label="Close" color="primary" flat />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </q-img>
                </q-icon>
              </template>
            </q-input>
          </div>
          <div style="width: 10%;font-size: 25px;font-weight: 600;color: #CBCBCB;text-align: center;">-</div>
          <div style="width: 45%;">
            <q-input borderless class="input-css" style="width: 100%;" v-model="weeklylist.enddate" dense hide-bottom-space
                     readonly>
            </q-input>
          </div>
        </div>

        <div style="width: 100%;text-align: right;margin-top: 30px;display: flex;justify-content: right;">
          <div>
            <div
              style="width: 148px;height: 40px;color: #ffffff;background: #1870C7;margin-right: 10px;border-radius: 5px;display: flex;align-items: center;"
              class="curPoint" @click="triggerFileUpload">
              <div style="width: 70%;display: flex;justify-content: center;align-items: center;line-height: 100%;">
                <label for="fileInput" class="custom-file-label" style="font-size: 16px;">Upload CSV</label>
                <input type="file" ref="fileInputRef" id="fileInput" @change="handleFileweek">
              </div>
              <q-icon style="width: 30%;height: auto ;color: #ffffff;font-size: 26.58px;" name="unarchive" />
            </div>
            <div style="width: 150px; font-weight: 400;text-align: left; overflow: hidden; white-space: nowrap;">
              <svg v-if="filetype == 1" width="8" height="8" viewBox="0 0 8 8" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <path fill-rule="evenodd" clip-rule="evenodd"
                  d="M1.24259 0.535511C1.04733 0.340249 0.73075 0.340249 0.535488 0.535511C0.340226 0.730774 0.340226 1.04736 0.535488 1.24262L3.36392 4.07104L0.535488 6.89947C0.340226 7.09473 0.340226 7.41132 0.535488 7.60658C0.730751 7.80184 1.04733 7.80184 1.2426 7.60658L4.07102 4.77815L6.89945 7.60658C7.09471 7.80184 7.41129 7.80184 7.60656 7.60658C7.80182 7.41132 7.80182 7.09473 7.60656 6.89947L4.77813 4.07104L7.60656 1.24262C7.80182 1.04736 7.80182 0.730773 7.60656 0.535511C7.41129 0.340249 7.09471 0.340249 6.89945 0.535511L4.07102 3.36394L1.24259 0.535511Z"
                  fill="#EB5E12" />
              </svg>
              <svg v-else-if="filetype == 2" width="10" height="10" viewBox="0 0 10 10" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <path d="M1 5.57143L4.2 9L9 1" stroke="#38B865" stroke-linecap="round" stroke-linejoin="round" />
              </svg>
              <svg v-else-if="filetype == 3" width="12" height="12" viewBox="0 0 12 12" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M11.25 6C11.25 7.27156 10.7885 8.49991 9.95124 9.45691C9.11396 10.4139 7.95782 11.0345 6.69753 11.2035C5.43724 11.3724 4.15846 11.0782 3.09871 10.3755C2.03895 9.6728 1.27024 8.60936 0.935351 7.38269C0.60046 6.15602 0.72215 4.84949 1.27782 3.70577C1.83349 2.56204 2.78537 1.65886 3.95667 1.16396C5.12797 0.669059 6.43908 0.616081 7.64649 1.01487C8.8539 1.41365 9.87555 2.23709 10.5217 3.33225"
                  stroke="url(#paint0_angular_499_1179)" stroke-width="1.5" stroke-linecap="round"
                  stroke-linejoin="bevel" />
                <defs>
                  <radialGradient id="paint0_angular_499_1179" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse"
                    gradientTransform="translate(6 6) rotate(-23.9625) scale(5.90931 5.92082)">
                    <stop stop-color="#31373D" />
                    <stop offset="1" stop-color="#31373D" stop-opacity="0" />
                  </radialGradient>
                </defs>
              </svg>
              {{ filename }}
            </div>
          </div>
          <button @click="exportweeek"
            style="cursor: pointer;width: 148px;height: 40px;color: #ffffff;background: #1870C7;margin-right: 10px;border: none;border-radius: 5px;display: flex;align-items: center;">
            <div style="width: 70%;;font-size: 16px;">Export CSV</div>
            <q-icon style="width: 30%;height: auto ;color: #ffffff;font-size: 26.58px;" name="archive" />
          </button>
        </div>
      </q-card-section>
    </q-card>
    <q-card class="q-pa-sm search-css card-radius">
      <div style="color: #303CBB;font-size: 1.6rem;font-weight: 500;display: flex;align-items: center;">
        <div style="margin-left: 15px;">Incident View Report</div>
      </div>
      <q-card-section class="q-gutter-y-sm row">
        <q-item-label class="col-4 fal">Job No./Work order No.</q-item-label>
        <q-input borderless v-model="listincident.parent_work_order_no" use-input input-debounce="0" hide-bottom-space
          lazy-rules class="col-8 fal input-css" :dense="true">
        </q-input>
        <q-item-label class="col-4 fal">Date Range</q-item-label>
        <div class="col-8  q-pa-sm" style="display: flex;align-items: center;justify-content: space-between;padding: 0;">
          <div style="width: 45%;">
            <q-input borderless class="input-css" v-model="listincident.start_date" dense hide-bottom-space readonly>
              <template v-slot:append>
                <img :src="delImg" alt="" v-if="listincident.start_date" @click="listincident.start_date = ''">
                <div v-else style="width:21px;height: 21px;"></div>
                <q-icon class="cursor-pointer ml4" size="md">
                  <q-img img :src="dateIcon">
                    <q-popup-proxy>
                      <q-date v-model="listincident.start_date">
                        <div class="row items-center justify-end">
                          <q-btn v-close-popup label="Close" color="primary" flat />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </q-img>
                </q-icon>
              </template>
            </q-input>
          </div>
          <div style="width: 10%;font-size: 25px;font-weight: 600;color: #CBCBCB;text-align: center;">-</div>
          <div style="width: 45%;">
            <q-input borderless class="input-css" v-model="listincident.end_date" dense hide-bottom-space readonly>
              <template v-slot:append>
                <img :src="delImg" alt="" v-if="listincident.end_date" @click="listincident.end_date = ''">
                <div v-else style="width:21px;height: 21px;"></div>
                <q-icon class="cursor-pointer ml4" size="md">
                  <q-img img :src="dateIcon">
                    <q-popup-proxy>
                      <q-date v-model="listincident.end_date">
                        <div class="row items-center justify-end">
                          <q-btn v-close-popup label="Close" color="primary" flat />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </q-img>
                </q-icon>
              </template>
            </q-input>
          </div>
        </div>
        <div style="width: 100%;text-align: right;margin-top: 30px;display: flex;justify-content: right;">
          <div>
            <div
              style="width: 148px;height: 40px;color: #ffffff;background: #1870C7;margin-right: 10px;border-radius: 5px;display: flex;align-items: center;"
              class="curPoint" @click="triggerFileUploadIncident">
              <div style="width: 70%;display: flex;justify-content: center;align-items: center;line-height: 100%;">
                <label for="fileInput1" class="custom-file-label" style="font-size: 16px;">Upload CSV</label>
                <input ref="fileInputRefIncident" type="file" id="fileInput1" @change="handleFileChange">
              </div>
              <q-icon style="width: 30%;height: auto ;color: #ffffff;font-size: 26.58px;" name="unarchive" />
            </div>
            <div style="width: 150px; font-weight: 400;text-align: left; overflow: hidden;  white-space: nowrap;">
              <svg v-if="incidentfiletype == 1" width="8" height="8" viewBox="0 0 8 8" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <path fill-rule="evenodd" clip-rule="evenodd"
                  d="M1.24259 0.535511C1.04733 0.340249 0.73075 0.340249 0.535488 0.535511C0.340226 0.730774 0.340226 1.04736 0.535488 1.24262L3.36392 4.07104L0.535488 6.89947C0.340226 7.09473 0.340226 7.41132 0.535488 7.60658C0.730751 7.80184 1.04733 7.80184 1.2426 7.60658L4.07102 4.77815L6.89945 7.60658C7.09471 7.80184 7.41129 7.80184 7.60656 7.60658C7.80182 7.41132 7.80182 7.09473 7.60656 6.89947L4.77813 4.07104L7.60656 1.24262C7.80182 1.04736 7.80182 0.730773 7.60656 0.535511C7.41129 0.340249 7.09471 0.340249 6.89945 0.535511L4.07102 3.36394L1.24259 0.535511Z"
                  fill="#EB5E12" />
              </svg>
              <svg v-else-if="incidentfiletype == 2" width="10" height="10" viewBox="0 0 10 10" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <path d="M1 5.57143L4.2 9L9 1" stroke="#38B865" stroke-linecap="round" stroke-linejoin="round" />
              </svg>
              <svg v-else-if="incidentfiletype == 3" width="12" height="12" viewBox="0 0 12 12" fill="none"
                xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M11.25 6C11.25 7.27156 10.7885 8.49991 9.95124 9.45691C9.11396 10.4139 7.95782 11.0345 6.69753 11.2035C5.43724 11.3724 4.15846 11.0782 3.09871 10.3755C2.03895 9.6728 1.27024 8.60936 0.935351 7.38269C0.60046 6.15602 0.72215 4.84949 1.27782 3.70577C1.83349 2.56204 2.78537 1.65886 3.95667 1.16396C5.12797 0.669059 6.43908 0.616081 7.64649 1.01487C8.8539 1.41365 9.87555 2.23709 10.5217 3.33225"
                  stroke="url(#paint0_angular_499_1179)" stroke-width="1.5" stroke-linecap="round"
                  stroke-linejoin="bevel" />
                <defs>
                  <radialGradient id="paint0_angular_499_1179" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse"
                    gradientTransform="translate(6 6) rotate(-23.9625) scale(5.90931 5.92082)">
                    <stop stop-color="#31373D" />
                    <stop offset="1" stop-color="#31373D" stop-opacity="0" />
                  </radialGradient>
                </defs>
              </svg>

              {{ incidentfilename }}
            </div>
          </div>
          <button @click="exportincdent"
            style="cursor: pointer;width: 148px;height: 40px;color: #ffffff;background: #1870C7;margin-right: 10px;border: none;border-radius: 5px;display: flex;align-items: center;">
            <div style="width: 70%;;font-size: 16px;">Export CSV</div>
            <q-icon style="width: 30%;height: auto ;color: #ffffff;font-size: 26.58px;" name="archive" />
          </button>
        </div>
      </q-card-section>
    </q-card>
  </div>
</template>

<script setup lang="ts">
import dateIcon from 'src/assets/style/date.png';
import delImg from 'src/assets/style/delImgs.png';
import { ref, reactive, onMounted, watch } from 'vue';
import { Notify, useQuasar } from 'quasar'
import ReportPage from 'src/pages/ReportPage.vue';
import { pdflist } from 'src/services/type';
import {
  getreportipi, getreportweeks, upload_cm_weekly_summary, upload_incident_view, get_incident_view
} from '../../services/PartDetailpdf'

import { getCurrentDate, getConvertDate } from 'src/utils/formatDate.js';
const createForm = reactive<{
  data: pdflist;
}>({
  data: {
    start_date: '',
    end_date: '',
    completed: false,
    stock_code: '',
  },
});
const $q = useQuasar()
onMounted(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
  const day = String(now.getDate()).padStart(2, '0');
  createForm.data.start_date = `${year}/${month}/${day}`;
  createForm.data.end_date = `${year}/${month}/${day}`;
});
const file = ref(null)
const filetype = ref(0)
const incidentfiletype = ref(0)
const incidentfile = ref(null)
const weeklylist = ref({
  orderid: '',
  datefrom: '',
  enddate: '',
})
const exportLoading = ref<boolean>(false)
const fileInputRef = ref(null);
const fileInputRefIncident = ref(null);
const maxFileSize = 5 * 1024 * 1024; // 文件大小最多上传的大小
watch(file, () => {
  Uploadfiles()
});
watch(incidentfile, () => {
  Uploadtincdent()
});
// watch weeklylist.datefrom change
watch(
    () => weeklylist.value.datefrom,
    (newDateFrom, oldDateFrom) => {
      //weeklylist.value.enddate equal to newDateFrom a week later
      if (newDateFrom != '') {
        const date = new Date(newDateFrom);
        date.setDate(date.getDate() + 6);
        weeklylist.value.enddate = getConvertDate(date);
      } else {
        weeklylist.value.enddate = ''
      }
    }
);
const incidentfilename = ref('')
const filename = ref('')
function handleFileweek(event) {
  if (!event.target.files[0]) return;
  file.value = event.target.files[0];
  if (event.target.files[0]?.size > maxFileSize) {
    $q.notify({
      message: 'File size is greater than 5 MB',
      color: 'negative',
    })
    return;
  }
  var maxLength = 16; // 指定要显示的字符数
  if (getByteLength(file.value.name) > maxLength) {
    var truncatedFilename = truncateChineseFilename(file.value.name, maxLength)
    filename.value = truncatedFilename
  } else {
    filename.value = file.value.name;
  }
}
const triggerFileUpload = (e) => {
  if (e.target.tagName === 'LABEL') return
  e.stopPropagation();
  fileInputRef.value?.click();
}
function handleFileChange(event) {
  if (!event.target.files[0]) return;
  incidentfile.value = event.target.files[0];
  if (event.target.files[0]?.size > maxFileSize) {
    $q.notify({
      message: 'File size is greater than 5 MB',
      color: 'negative',
    })
    return;
  }
  var maxLength = 16; // 指定要显示的字符数
  if (getByteLength(incidentfile.value.name) > maxLength) {
    var truncatedFilename = truncateChineseFilename(incidentfile.value.name, maxLength)
    incidentfilename.value = truncatedFilename
  } else {
    incidentfilename.value = incidentfile.value.name;
  }
}

function truncateChineseFilename(filename, maxLength) {
  if (getByteLength(filename) <= maxLength) {
    // 如果文件名长度不超过 maxLength，直接返回文件名
    return filename;
  }

  var byteLen = 0;
  var truncatedStart = '';
  var truncatedEnd = '';

  // 获取前面八个字符，考虑中文字符的字节长度
  for (var i = 0; i < filename.length; i++) {
    var charCode = filename.charCodeAt(i);
    byteLen += (charCode <= 255) ? 1 : 2;

    if (byteLen > 7) {
      break;
    }
    truncatedStart += filename[i];
  }

  // 获取后面八个字符，考虑中文字符的字节长度
  byteLen = 0;
  for (var j = filename.length - 1; j >= 0; j--) {
    var charCodeEnd = filename.charCodeAt(j);
    byteLen += (charCodeEnd <= 255) ? 1 : 2;

    if (byteLen > 8) {
      break;
    }
    truncatedEnd = filename[j] + truncatedEnd;
  }

  // 返回组合后的字符串
  return truncatedStart + '...' + truncatedEnd;
}
function getByteLength(str) {
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);
    if (code <= 0x7f) {
      len += 1;
    } else if (code >= 0x80 && code <= 0x7ff) {
      len += 2;
    } else if (code >= 0x800 && code <= 0xffff) {
      len += 3;
    } else {
      len += 4;
    }
  }
  return len;
}


async function exportincdent() {
  try {
    exportLoading.value = true;
    const res = await get_incident_view(listincident.value.parent_work_order_no, listincident.value.start_date, listincident.value.end_date);
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(res.data);
    let text = `Incident_View_Report_${getCurrentDate()}.csv`?.replace(/-/g,'_');
    link.download = text
    link.click();
    link.remove();
  } catch (error) {
    $q.notify({
      color: 'negative',
      position: 'bottom',
      message: 'Data not found',
    })
  }finally {
    exportLoading.value = false;
  }
}
async function Uploadtincdent() {
  if (incidentfile.value?.size > maxFileSize) return;
  incidentfiletype.value = 3
  const res = await upload_incident_view(incidentfile.value);
  const { code, message } = res.data;
  if (code == 1) {
    incidentfiletype.value = 2
    $q.notify({
      message: 'success',
      color: 'primary',
    })
  } else if ([0,-2].includes(code)) {
    const resultMessage = code==-2 && message?.map((item:any) => `<div>${item}</div>`).join('') || 'Error';
    incidentfiletype.value = 1
    $q.dialog({
      title: 'Promp',
      html: true,
      message: code==-2? resultMessage : message,
    })
  }else {
    incidentfiletype.value = 1
    $q.notify({
      color: 'negative',
      message,
    });
  }
}
async function Uploadfiles() {
  if (file.value?.size > maxFileSize) return;
  filetype.value = 3
  const res = await upload_cm_weekly_summary(file.value)
  const { code, message } = res.data;
  if (code == 1) {
    filetype.value = 2
    $q.notify({
      message: 'success',
      color: 'primary',
    })
  }else if ([0,-2].includes(code)) {
    const resultMessage = code==-2 && message?.map((item:any) => `<div>${item}</div>`).join('') || 'Error';
    filetype.value = 1
    $q.dialog({
      title: 'Promp',
      html: true,
      message: code==-2? resultMessage : message,
    })
  } else {
    incidentfiletype.value = 1
    $q.notify({
      color: 'negative',
      message,
    });
  }
}
function optionsFn(data) {
  const currentDate = new Date()
  const sevenDaysAgo = new Date(currentDate.getTime() - 5 * 24 * 60 * 60 * 1000);
  return data < sevenDaysAgo.getFullYear() + '/' + (sevenDaysAgo.getMonth() + 1).toString().padStart(2, '0') + '/' + sevenDaysAgo.getDate().toString().padStart(2, '0');
}
async function exportweeek() {
  try {
    const res = await getreportweeks(weeklylist.value.orderid, weeklylist.value.datefrom);
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(res.data);
    let text = `CEWS_Weekly_Summary_Report_${getCurrentDate()}.csv`?.replace(/-/g,'_');
    link.download = text
    link.click();
    link.remove();
  } catch (error) {
    $q.notify({
      color: 'negative',
      position: 'bottom',
      message: 'Data not found',
    })
  }
}
const listincident = ref({
  parent_work_order_no: '',
  start_date: '',
  end_date: ''
})

/**
 * 下载 IGI_report 的文件
 */
async function IgiReportDownload() {
  const res = await getreportipi(createForm.data.completed, createForm.data.stock_code, createForm.data.start_date, createForm.data.end_date);
  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(res.data);
  let text = `IGI_report_${getCurrentDate()}.pdf`?.replace(/-/g,'_');
  link.download = text
  link.click();
  link.remove();
}
const triggerFileUploadIncident = (e) => {
  if (e.target.tagName === 'LABEL') return
  e.stopPropagation();
  fileInputRefIncident.value?.click();
}
</script>

<style scoped>
.timeclass {
  padding: 0;
}

input[type="file"] {
  display: none;
}

/* 自定义文件选择器的文本样式 */
.custom-file-label {
  cursor: pointer;
}

.ml4 {
  margin-left: 4px;
}

.btnExportText {
  font-weight: bold;
  margin-right: 10px;
}

.curPoint {
  cursor: pointer;
}

.inputClass {
  position: fixed;
  left: -9999px;
  top: -9999px;
}
</style>
